package whr.modules.sys.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import whr.common.annotation.SysLog;
import whr.common.utils.PageUtils;
import whr.common.utils.R;
import whr.common.utils.ResponseApi;
import whr.common.utils.UserExcelUtil;
import whr.common.validator.Assert;
import whr.common.validator.ValidatorUtils;
import whr.common.validator.group.AddGroup;
import whr.common.validator.group.UpdateGroup;
import whr.modules.sys.entity.SysUserEntity;
import whr.modules.sys.form.PasswordForm;
import whr.modules.sys.service.SysUserRoleService;
import whr.modules.sys.service.SysUserService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
//    @Autowired
//    private String basePath;
    @Value("${web.upload-path}")
    private String uploadPath;




    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    public R list(@RequestParam Map<String, Object> params) {
        log.info("params{}", params);
        //只有超级管理员，才能查看所有管理员列表
//		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
//		}
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 获取登录的用户信息
     */
    @GetMapping("/info")
    public R info() {
        return R.ok().put("user", getUser());
    }

    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @PostMapping("/password")
    public R password(@RequestBody PasswordForm form) {
        Assert.isBlank(form.getNewPassword(), "新密码不为能空");

        //sha256加密
        String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
        //sha256加密
        String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @GetMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = sysUserService.getById(userId);

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
        user.setRoleIdList(roleIdList);
        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
//		user.setPassword(Compents.INIT_PWD); //初始密码为123456
        user.setCreateUserId(getUserId());
        //根据邮箱判断是否已存在

        sysUserService.saveUser(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @PostMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        user.setCreateUserId(getUserId());
        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @PostMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }
        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }
        sysUserService.deleteBatch(userIds);

        return R.ok();
    }

    /*
     * 查询当前角色为面试官的用户
     * */
    @RequestMapping("/getInterviewer")
    public R getInterviewer() {
        List<SysUserEntity> interviewers = sysUserRoleService.queryInterviewer();
        return R.ok().put("interviewers", interviewers);
    }

    //查询用户的总数
    @RequestMapping("/getUserCount")
    public ResponseApi getUserCount() {
        return ResponseApi.success(sysUserService.getUserCount());
    }

    //查询每个部门的人数
    @RequestMapping("/getUserCountByDept")
    public ResponseApi getUserCountByDept() {
        return ResponseApi.success(sysUserService.getUserCountByDept());
    }

    //导出Excle文件
    @PostMapping("/export")
    public R exportData(@RequestBody Integer[] ids, HttpServletResponse response) {
        System.out.println(ids);
        System.out.println(response);

        //1、要导出的数据
        List<SysUserEntity> userEntityList = sysUserService.selectUserListInIds(Arrays.asList(ids));
        //2、导出excel
        UserExcelUtil ueu = new UserExcelUtil();
        ueu.exportData(userEntityList, response);
        return null;
    }


    /**
     * 导入Excel文件
     * @param file
     * @return
     */
    @PostMapping("/import")
    public R importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream()); //读取Excel文件
        List<SysUserEntity> sysUserEntityList = reader.readAll(SysUserEntity.class);//读取所有的数据
        try {
            sysUserService.saveBatch(sysUserEntityList);  //写入数据到数据库
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("数据批量导入错误");
        }

        return R.ok();
    }

    //用户头像的上传,数据中存头像路径
    @PostMapping("/updateUserAvatar")
    @ApiOperation(value = "修改头像", notes = "修改头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "头像", required = true, dataType = "MultipartFile", paramType = "query"),
            @ApiImplicitParam(name = "user_id", value = "用户id", required = true, dataType = "int", paramType = "query")
    })
    public ResponseApi updateUserAvatar(
            @RequestParam(value = "file") List<MultipartFile> files,
            @RequestParam("user_id") int user_id){
        if(files==null || files.isEmpty()){
            throw new IllegalArgumentException("文件不能为空");
        }
        System.out.println("文件"+files.size());
        System.out.println("用户id"+user_id);
        return sysUserService.updateUserAvatarById(files,user_id);
    }





    //文件上传
//    @RequestMapping("/upload")
//    public  void upload( MultipartFile file, HttpServletRequest req) throws IOException {
//
//        File folder = new File(uploadPath);
//        if (!folder.isDirectory()) {
//            folder.mkdirs();
//        }
//        // 对上传的文件重命名，避免文件重名
//        String oldName =  file.getOriginalFilename();
//        String newName = UUID.randomUUID().toString()
//                + oldName.substring(oldName.lastIndexOf("."), oldName.length());
//        // 文件保存
//        file.transferTo(new File(folder, newName));
//        // 返回上传文件的访问路径
//        String filePath = req.getScheme() + "://" + req.getServerName()
//                + ":" + req.getServerPort() +"/"  + newName + "?token=0b748d798874359ef6819ee0a2821ab4";
//        /*System.out.println("文件地址:"+ folder+newName);*/
//        SysUserEntity sysUserEntity = new SysUserEntity();
//        sysUserEntity.setUserId(1L);
////        sysUserEntity.setAvatar(filePath);
//        sysUserService.update(sysUserEntity);
//    }

//
//    //头像上传
//    @PostMapping("/uploadAvatar")
//    public ResponseApi<String> updateUserAvatar(MultipartFile file){
//        //file是一个临时文件，需要转存到指定位置，否则本次请求完成之后会删除
//        log.info(file.toString());
//
//        //原始文件名
//        String originalFilename =file.getOriginalFilename();
//        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
//
//        //使用UUID重新生成文件名，防止文件名重复造成文件覆盖
//        String fileName = UUID.randomUUID().toString()+suffix;
//
//        //创建一个目录对象
//        File dir=new File(basePath);
//        if(!dir.exists()){
//            //目录不存在，需要创建
//            dir.mkdir();
//        }
//        try {
//            //将临时文件转存到指定位置
//            file.transferTo(new File(basePath+fileName));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return ResponseApi.success(fileName);
//    }
//
//    //文件下载
//    @GetMapping("/download")
//    public void download(String fileName, HttpServletResponse response){
//        try {
//            //输入流，通过输入流读取文件内容
//            FileInputStream fileInputStream=new FileInputStream(basePath+fileName);
//
//            //输出流，通过输出流将文件写回浏览器，在浏览器展示图片
//            ServletOutputStream outputStream = response.getOutputStream();
//
//            response.setContentType("image/jpeg");
//
//            int len=0;
//            byte[] bytes=new byte[1024];
//            while((len = fileInputStream.read(bytes))!=-1){
//                outputStream.write(bytes,0,len);
//                outputStream.flush();
//            }
//            //释放资源
//            outputStream.close();
//            fileInputStream.close();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
}
